package com.woniuxy.security;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.controller.info.AccountInfo;
import com.woniuxy.controller.info.AccountLogininfo;
import com.woniuxy.controller.info.UserInfo;
import com.woniuxy.dao.ResourceDao;
import com.woniuxy.utils.NewCopyBean;
import com.woniuxy.utils.ObjectRedisTemplate;
import com.woniuxy.utils.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private ResourceDao resourceDao;

    @Resource
    private ObjectRedisTemplate ort;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        Integer accountId = ((AccountLogininfo) authentication.getPrincipal()).getAccountId();
        List<String> resourceUri = resourceDao.findResourceUri(accountId);
        UserInfo userInfo = new UserInfo();
        userInfo.setAccountId(accountId);
        userInfo.setAccountUsername(((AccountLogininfo) authentication.getPrincipal()).getAccountUsername());
        userInfo.setUris(resourceUri);
        //存入redis

        ort.opsForValue().set("Account:info:id:"+accountId,userInfo,60*60, TimeUnit.SECONDS);
        request.getSession().setAttribute("AccountId",accountId);

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        AccountInfo accountInfo = NewCopyBean.copyOne(authentication.getPrincipal(), AccountInfo.class);
        Result result = Result.success(200, "登陆成功", accountInfo);
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();

    }
}
